package com.lu.banklogin.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.banklogin.mapper.UserMapper;
import com.lu.banklogin.pojo.dto.LoginDTO;
import com.lu.banklogin.pojo.entity.User;
import com.lu.banklogin.service.UserService;
import com.lu.banklogin.utils.JwtUtil;
import com.lu.banklogin.utils.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author L
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public ResultUtil login(LoginDTO dto) {

        if (Objects.isNull(dto)){
            return ResultUtil.fail("用户名和密码不能为空");
        }
        //拿到用户信息
        User user = userMapper
                .selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, dto.getUsername()));
        if (Objects.isNull(user)){
            return ResultUtil.fail("账号或密码错误");
        }
        //如果密码不相同逻辑
        if (!user.getPassword().equals(dto.getPassword())){
            return ResultUtil.fail("账号或密码错误");
        }

        String token = JwtUtil.generateToken(dto.getUsername(), dto.getPassword(), 300);
        HashMap<String, String> map = new HashMap<>(2);
        map.put("token",token);
        return ResultUtil.success(map);
    }

    @Override
    public Boolean verify(String token) {
        if (Objects.isNull(token)){
            return false;
        }
        if (token.isEmpty()){
            return false;
        }
        JSONObject jsonObject = JwtUtil.verifyToken(token);

        User user = userMapper
                .selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername,jsonObject.get("username")));
        if (Objects.isNull(user)){
            return false;
        }
        //如果密码不相同逻辑
        return user.getPassword().equals(jsonObject.get("password"));
    }

    @Override
    public User verify2(String token) {
        JSONObject jsonObject = JwtUtil.verifyToken(token);

        return userMapper
                .selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername,jsonObject.get("username")));
    }
}
